from StringIO import StringIO
from string import upper, lower
from defect import Defect

__author__ = 'romilly'

class BufferReader:
    def __init__(self, string):
        self.buffer = StringIO(string)

    def hasMore(self):
        self.nextChar = self.buffer.read(1)
        return len(self.nextChar)

    def skip(self):
        self.hasMore() # reads the next character

class AbstractNameMangler():
    def mangleName(self, fieldName):
        if not len(fieldName):
            raise Defect('field name canot be empty')
        buffer = StringIO()
        for char in fieldName:
            if char.isupper():
                buffer.write('_')
            buffer.write(upper(char))
        return buffer.getvalue()

    def makeTableName(self, className):
        if not len(className):
            raise Defect('class name cannot be empty')
        return upper(className[0])+self.mangleName(className[1:])

class SmalltalkNameMangler(AbstractNameMangler):
    def makeColumnName(self, fieldName):
        return self.mangleName(fieldName)

    def makeFieldName(self, columnName):
        ibuffer = BufferReader(columnName)
        obuffer = StringIO()
        while ibuffer.hasMore():
            if ibuffer.nextChar == '_':
                ibuffer.skip()
                obuffer.write(upper(ibuffer.nextChar))
            else:
                obuffer.write(lower(ibuffer.nextChar))
        return obuffer.getvalue()

class PythonNameMangler(AbstractNameMangler):
    def makeColumnName(self, fieldName):
        return upper(fieldName)

    def makeFieldName(self, columnName):
        return lower(columnName)



  